package eao;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import entity.Product;

@Stateless(mappedName="eaoProduct")
@LocalBean
public class EaoProduct {

	@PersistenceContext
	private EntityManager em;
    
	public EaoProduct() {}
    
    public Product find(int id) {
        return em.find(Product.class, id);
    }

    public List<Product> list() {
    	return em.createQuery("SELECT p FROM Product p", Product.class).getResultList();
    }

    public void create(Product product) throws Exception {
        try{
        	em.persist(product);
        	em.flush();
        }catch (Exception e) {
        	throw new Exception(e.getMessage());
		}
    }

    public void update(Product product) {
        em.merge(product);
    }

    public void delete(Product product) {
        em.remove(em.contains(product) ? product : em.merge(product));
    }

    public List<Product> search(String name){
    	return em.createQuery("SELECT p FROM Product as p WHERE p.name LIKE :name", Product.class)
    			 .setParameter("name", "%"+ name + "%")
    			 .getResultList();
    }
    
    public List<Product> listLastest(int first, int last){
    	return em.createQuery("SELECT p FROM Product as p ORDER BY p.id DESC", Product.class)
    			.setFirstResult(first)
    			.setMaxResults(last)
    			.getResultList();
    }
    
    
    
}
